package cn.caplike.demo.nio._2017;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.StandardCharsets;

/**
 * 简介：DatagramChannel
 *
 * @author 李珂 2017年11月22日 下午5:39:06
 */
public class DatagramChannelTest {

    public static void runReciever() throws IOException {
        DatagramChannel channel = DatagramChannel.open();
        channel.socket().bind(new InetSocketAddress(5000));
        channel.configureBlocking(false);

        ByteBuffer receiveBuf = ByteBuffer.allocate(48);
        /**
         * 1. 因为UDP是无连接的网络协议，所以不能像TCP那样读取和写入，它是发送和接收数据包。<br>
         * 2. receive()在非阻塞模式中，若没有收到数据包，则返回null；<br>
         * 若收到了，则将内容写入byteBuffer，将发送方的SocketAddress返回（其中包含IP和端口）<br>
         * 3. 如果Buffer容不下收到的数据，多出的数据将被丢弃；<br>
         */
        while (channel.receive(receiveBuf) == null) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        receiveBuf.flip();
        System.out.println("data: " + new String(receiveBuf.array(), StandardCharsets.UTF_8));
        channel.close();
    }

    public static void runSender() throws IOException {
        DatagramChannel channel = DatagramChannel.open();
        ByteBuffer sendBuf = ByteBuffer.allocate(48);
        sendBuf.put("李珂".getBytes());
        sendBuf.flip();

        channel.send(sendBuf, new InetSocketAddress("127.0.0.1", 5000));// 指定接收方的SocketAddress
        channel.close();
    }

}
